/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.wizards.template;

import cn.easyplatform.entities.beans.list.Header;
import cn.easyplatform.entities.beans.list.ListBean;
import cn.easyplatform.entities.beans.page.PageBean;
import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.entity.CheckCmd;
import cn.easyplatform.studio.cmd.entity.GetEntityCmd;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.web.editors.*;
import cn.easyplatform.studio.web.editors.support.CodeFormatter;
import cn.easyplatform.studio.web.editors.support.ZulXsdUtil;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import cn.easyplatform.type.EntityType;
import org.apache.commons.lang3.math.NumberUtils;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class Page1 extends Page0 {

    private Grid list;

    protected TableInfo selectedTable;

    protected String selectedList;

    @Override
    protected void initComponents(Component root) {
        super.initComponents(root);
        list = (Grid) root.getFellow("page_grid_list");
        //root.getFellow("page_button_selectList").addEventListener(Events.ON_CLICK, this);
    }

    @Override
    protected void dispatch(final Event evt) {
        super.dispatch(evt);
        final Component c = evt.getTarget();
        if (c == list) {
            selectedTable = (TableInfo) evt.getData();
            onCreate(list, selectedTable);
        } else if (c.getId().equals("page_button_selectList")) {
            AbstractView.createComponentView(new EditorCallback<String>() {
                @Override
                public String getValue() {
                    return selectedList;
                }

                @Override
                public void setValue(String value) {
                    selectedList = value;
                    onSelect(list, selectedList);
                }

                @Override
                public String getTitle() {
                    return ((Button) c).getLabel();
                }

                @Override
                public Page getPage() {
                    return c.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            },EntityType.DATALIST.getName(), c).doHighlighted();
        } else if (c.getId().equals("page_button_addList")) {
            AbstractView.createTableView(new EditorCallback<TableInfo>() {
                @Override
                public TableInfo getValue() {
                    return selectedTable;
                }

                @Override
                public void setValue(TableInfo value) {
                    selectedTable = value;
                    onCreate(list, selectedTable);
                }

                @Override
                public String getTitle() {
                    return Labels.getLabel("wizard.table");
                }

                @Override
                public Page getPage() {
                    return list.getPage();
                }

                @Override
                public Editor getEditor() {
                    return null;
                }
            }, true, evt.getTarget()).doOverlapped("right,center");
        }
    }

    @Override
    public PageBean getEntity() {
        save();
        PageBean pb = new PageBean();
        pb.setTable(mainTable == null ? null : mainTable.getTable());
        pb.setAjax(getContent());
        return pb;
    }

    protected String fetchId() {
        Component component = list.getRoot();
        String id = (String) list.getRoot().getAttribute("id");
        if (id.length() > 4) {
            // 功能ID：SYSCOM50
            // 页面ID：SYSCOM50PY01
            // 列表ID：SYSCOM50QY01
            // 子表列表：SYSCOM50QY02
            // 子表页面：SYSCOM50PY02
            String suffix = id.substring(id.length() - 4, id.length());
            String preffix = id.substring(0, id.length() - 4);
            if (suffix.startsWith("PY")
                    && NumberUtils.isNumber(suffix.substring(2))) {// 符合id命名规范
                for (int i = 1; i <= 99; i++) {
                    String entityId = preffix + "QY" + (i < 10 ? "0" + i : i);
                    if (!StudioApp.execute(new CheckCmd(entityId))) {
                        id = entityId;
                        break;
                    }
                }
            } else {// 不符合规范的,在页面id的基础上从01开始累加
                for (int i = 1; i <= 99; i++) {
                    String entityId = id + (i < 10 ? "0" + i : i);
                    if (!StudioApp.execute(new CheckCmd(entityId))) {
                        id = entityId;
                        break;
                    }
                }
            }
        } else {// 不符合规范的,在页面id的基础上从01开始累加
            for (int i = 1; i <= 99; i++) {
                String entityId = id + (i < 10 ? "0" + i : i);
                if (!StudioApp.execute(new CheckCmd(entityId))) {
                    id = entityId;
                    break;
                }
            }
        }
        return id;
    }

    protected void save() {
        if (selectedTable != null) {
            ListBean bean = new ListBean();
            bean.setTable(selectedTable.getTable());
            bean.setId(fetchId());
            bean.setType(EntityType.DATALIST.getName());
            bean.setName((String) list.getRoot().getAttribute("name"));
            List<Header> headers = new ArrayList<Header>();
            for (TableField tf : selectedTable.getFields()) {
                Header header = new Header();
                header.setField(tf.getName());
                header.setName(tf.getName());
                header.setTitle(tf.getDescription());
                header.setType(tf.getType());
                headers.add(header);
            }
            bean.setHeaders(headers);
            StudioUtil.save(bean, 'C');
            this.selectedList = bean.getId();
        }
    }

    @Override
    protected String getContent() {
        return buildPage("north");
    }

    protected String buildPage(String layout) {
        String main = super.getContent();
        StringBuilder sb = new StringBuilder();
        sb.append("<borderlayout>");
        if (layout.equals("east") || layout.equals("west")) {
            sb.append("<")
                    .append(layout)
                    .append(" border=\"none\" width=\"300px\" margins=\"5,5,5,5\">");
            buildListToolbar(sb);
            if (Strings.isBlank(selectedList) == false)
                buildList(sb);
            sb.append("</").append(layout).append(">");
            sb.append("<center border=\"none\" hflex=\"1\" vflex=\"1\">");
            sb.append(main);
            sb.append("</center>");
        } else {
            sb.append("<").append(layout)
                    .append(" border=\"none\" margins=\"5,5,5,5\" size=\"70%\">");
            sb.append(main);
            sb.append("</").append(layout).append(">");
            sb.append("<center border=\"none\" hflex=\"1\" vflex=\"1\">");
            buildListToolbar(sb);
            if (Strings.isBlank(selectedList) == false)
                buildList(sb);
            sb.append("</center>");
        }
        sb.append("</borderlayout>");
        return CodeFormatter.formatXML(ZulXsdUtil.buildDocument(sb
                .toString()));
    }

    protected void buildListToolbar(StringBuilder sb) {
    }

    protected void buildList(StringBuilder sb) {
        sb.append("<datalist entity=\"").append(selectedList).append("\"")
                .append(" id=\"pageList\"");
        sb.append(
                " hflex=\"1\" vflex=\"1\" durable=\"true\" event=\"open('U')\"")
                .append(" showRowNumbers=\"true\" pageSize=\"20\"")
                .append(" sizedByContent=\"true\" span=\"true\"/>");
    }

    protected void onSelect(Grid grid, String id) {
        ListBean bean = (ListBean) StudioApp.execute(new GetEntityCmd(id));
        grid.getColumns().getChildren().clear();
        for (Header header : bean.getHeaders()) {
            Column col = new Column();
            col.appendChild(new Label(header.getTitle()));
            col.setTooltiptext(header.getName());
            col.setAlign(header.getAlign());
            col.setStyle(header.getStyle());
            col.setIconSclass(header.getIconSclass());
            col.setImage(header.getImage());
            if (!Strings.isBlank(header.getWidth()))
                col.setWidth(header.getWidth());
            grid.getColumns().appendChild(col);
        }
        if (Strings.isBlank(bean.getHeaders().get(0).getName()))
            WebUtils.showInfo(Labels.getLabel("create.table.noDes"));
    }

    protected void onCreate(Grid grid, TableInfo tables) {
        grid.getColumns().getChildren().clear();
        for (TableField tf : tables.getFields()) {
            Column col = new Column(tf.getDescription());
            col.setTooltiptext(tf.getName());
            col.setWidth("120px");
            grid.getColumns().appendChild(col);
        }
        if (Strings.isBlank(tables.getFields().get(0).getDescription()))
            WebUtils.showInfo(Labels.getLabel("create.table.noDes"));
    }

    @Override
    protected void buildToolbar(StringBuilder sb, String align) {
        sb.append("<row").append(" spans=\"").append(cols.getValue())
                .append("\"");
        if (align.equals("center"))
            sb.append(" align=\"center\"");
        else if (align.equals("right"))
            sb.append(" align=\"right\"");
        sb.append(">").append("<div>");
        ;
        sb.append("<button label=\"").append(Labels.getLabel("button.add"))
                .append("\" event=\"create()\"")
                .append(" iconSclass=\"z-icon-plus\"/>");
        sb.append("<button label=\"").append(Labels.getLabel("button.delete"))
                .append("\" event=\"remove();pageList.reload()\"")
                .append(" iconSclass=\"z-icon-minus\"/>");
        sb.append("<button label=\"").append(Labels.getLabel("button.save"))
                .append("\" event=\"save();pageList.reload()\"")
                .append(" iconSclass=\"z-icon-save\"/>");
        sb.append("</div>").append("</row>");
    }

}
